<template>
  <div class="login_box">
    <el-form
      ref="ruleFormRef"
      style="max-width: 500px"
      :model="userInfo"
      status-icon
      :rules="rules"
      label-width="auto"
      class="ruleForm"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="userInfo.username" type="text" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="userInfo.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登陆</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {reactive,ref} from 'vue'
import { useRouter } from 'vue-router'
import {userlogin} from '@/request/api'
const $router = useRouter()
const ruleFormRef = ref()
// 登陆
const login = ()=>{
    ruleFormRef.value.validate(async (val)=>{
        // val 验证通过为真
        if(!val){
            return
        }
        try{
            let res = await userlogin(userInfo.value)
            if(res.code == 200){
                ElMessage.success(res.msg)
                console.log(res);
                localStorage.setItem('userinfo', JSON.stringify(res.list) )
                setTimeout(()=>{
                  $router.push('/index/home')
                },3000)
            }else{
                ElMessage.warning(res.msg)
            }
        }catch(err){
            ElMessage.error(err)
        }
    })
}

let userInfo = ref({
    username:'admin',
    password:'111111'
})
// 验证规则
const rules = reactive({
    username:[
        {
            required:true,  // 是否为必填项
            message:'请输入用户名',  // 提示信息
            trigger:'blur'  // 触发方式  blur | change
        },
        {
            min:2,max:8,message:'长度在2到8个字符',trigger:'blur'
        }
    ],
    password:[
        {
            required:true,  // 是否为必填项
            message:'请输入密码',  // 提示信息
            trigger:'blur'  // 触发方式  blur | change
        },
        {
            min:6,max:18,message:'长度在6到18个字符',trigger:'blur'
        }
    ]
})
</script>

<style scoped>
.login_box{
    width:100vw;
    height:100vh;
    background:#eaeaea;
}
.ruleForm{
    position:absolute;
    left:50%;
    top:50%;
    transform: translate(-70%,-50%);
}
</style>